<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import userService from '../services/userService'
import type { LoginRequest } from '../types'

const router = useRouter()
const route = useRoute()

const formData = ref<LoginRequest>({
  identifier: '',
  password: '',
  rememberMe: false
})

const loading = ref(false)
const error = ref('')

// 处理登录
const handleLogin = async () => {
  // 表单验证
  if (!formData.value.identifier || !formData.value.password) {
    error.value = '请输入用户名/邮箱和密码'
    return
  }

  loading.value = true
  error.value = ''

  try {
    await userService.login(formData.value)
    
    // 登录成功，跳转到之前的页面或首页
    const redirect = route.query.redirect as string
    if (redirect) {
      router.push(redirect)
    } else {
      router.push('/')
    }
  } catch (err: any) {
    error.value = err.response?.data?.message || '登录失败，请检查您的用户名和密码'
  } finally {
    loading.value = false
  }
}

// 模拟登录功能（用于演示）
const mockLogin = async () => {
  loading.value = true
  error.value = ''

  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟登录成功，保存到localStorage
    const mockUser = {
      id: '1',
      username: 'demo',
      email: 'demo@example.com',
      avatar: 'https://via.placeholder.com/150',
      nickname: '演示用户',
      gender: 'male',
      bio: '这是一个演示用户',
      preferences: {},
      createdAt: new Date(),
      updatedAt: new Date(),
      lastLogin: new Date(),
      totalGames: 0,
      wins: 0,
      points: 0
    }
    
    localStorage.setItem('token', 'mock-token-123456')
    localStorage.setItem('userInfo', JSON.stringify(mockUser))
    
    // 登录成功，跳转到首页
    const redirect = route.query.redirect as string
    if (redirect) {
      router.push(redirect)
    } else {
      router.push('/')
    }
  } catch (err) {
    error.value = '模拟登录失败'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-header">
        <h2>欢迎登录</h2>
        <p>探索无限可能的海龟汤世界</p>
      </div>
      
      <div class="login-form card">
        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
        
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <label for="identifier">用户名/邮箱</label>
            <input
              id="identifier"
              v-model="formData.identifier"
              type="text"
              placeholder="请输入用户名或邮箱"
              required
              :disabled="loading"
            />
          </div>
          
          <div class="form-group">
            <label for="password">密码</label>
            <input
              id="password"
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              required
              :disabled="loading"
            />
          </div>
          
          <div class="form-group remember-me">
            <label>
              <input
                v-model="formData.rememberMe"
                type="checkbox"
                :disabled="loading"
              />
              记住我
            </label>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>
          
          <div class="form-actions">
            <button
              type="submit"
              class="btn-primary"
              :disabled="loading"
            >
              {{ loading ? '登录中...' : '登录' }}
            </button>
          </div>
        </form>
        
        <!-- 演示登录按钮 -->
        <div class="demo-section">
          <button
            @click="mockLogin"
            class="btn-demo"
            :disabled="loading"
          >
            演示登录
          </button>
          <p class="demo-tip">点击演示登录可直接体验系统功能</p>
        </div>
        
        <div class="register-link">
          还没有账号？<a href="/register">立即注册</a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  min-height: calc(100vh - 120px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.login-container {
  width: 100%;
  max-width: 420px;
  padding: 0 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: #262626;
  margin-bottom: 8px;
}

.login-header p {
  color: #666;
  font-size: 16px;
}

.login-form {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
}

.error-message {
  background-color: #fff1f0;
  border: 1px solid #ffccc7;
  color: #ff4d4f;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.remember-me {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.remember-me label {
  display: flex;
  align-items: center;
  margin: 0;
  cursor: pointer;
  font-weight: normal;
  font-size: 14px;
}

.remember-me input[type="checkbox"] {
  width: auto;
  margin-right: 6px;
  cursor: pointer;
}

.forgot-password {
  color: #1890ff;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

.forgot-password:hover {
  color: #40a9ff;
}

.form-actions {
  margin-bottom: 24px;
}

.btn-primary {
  width: 100%;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background-color: #40a9ff;
}

.btn-primary:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.demo-section {
  text-align: center;
  margin-bottom: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.btn-demo {
  width: 100%;
  padding: 12px;
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-demo:hover:not(:disabled) {
  background-color: #e6f7ff;
}

.btn-demo:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.demo-tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-form {
    padding: 24px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}
</style>